import { defineStore } from 'pinia'
import { getUser } from '@/api/user'
import { removeToken } from '@/utils/token'
import { login } from '@/api/auth'
import { createLocalStorage } from '@/utils/cache'

export const useUserStore = defineStore('user', {
  state() {
    return {
      userInfo: {},
    }
  },
  getters: {
    userId() {
      return this.userInfo?.id
    },
    name() {
      return this.userInfo?.name
    },
    avatar() {
      return this.userInfo?.avatar
    },
    role() {
      return this.userInfo?.role || []
    },
  },
  actions: {
    async getUserInfo() {
      try {
        const ls = createLocalStorage({ prefixKey: 'login_' })
        const lsLoginInfo = ls.get('loginInfo')
        const res = await login({ username: lsLoginInfo.username, password: lsLoginInfo.password.toString() })

        if (res.code === 1) {
          this.userInfo = { id: res.userid, name: res.username, avatar: null, role: [res.role] }
          // return Promise.resolve(res.data)
        } else {
          // return Promise.reject(res.message)
        }
      } catch (error) {
        console.error(error)
        return Promise.reject(error.message)
      }

      // const lsLoginInfo = ls.get('loginInfo')
      // const res = await login({ username: lsLoginInfo.username, password: lsLoginInfo.password.toString() })
      // this.userInfo = { id: res.userid, name: res.username, avatar: null, role: [res.role] }

      // try {
      //   const res = await getUser()
      //   if (res.code === 0) {
      //     const { id, name, avatar, role } = res.data
      //     this.userInfo = { id, name, avatar, role }
      //     return Promise.resolve(res.data)
      //   } else {
      //     return Promise.reject(res.message)
      //   }
      // } catch (error) {
      //   console.error(error)
      //   return Promise.reject(error.message)
      // }
    },
    logout() {
      removeToken()
      this.userInfo = {}
    },
    //设置用户信息
    setUserInfo(userInfo = {}) {
      this.userInfo = { ...this.userInfo, ...userInfo }
    },
  },
})
